package ar.com.framenet.base.service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.persistence.criteria.Expression;

import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import ar.com.framenet.base.dao.SimpleHibernateDAO;

@Transactional
@Service("datastoreService")
@SuppressWarnings("rawtypes")
public class DatastoreService {

	@Autowired
	private BeanFactory beanFactory;

	public List read(String entityName, Map filters) {
		List result = null;
		System.out.println("DatastoreServiceImpl.read()...");

		SimpleHibernateDAO daoSimple = (SimpleHibernateDAO) beanFactory.getBean("simpleHibernateDAO");
		daoSimple.setPersistentClass(entityName);
		
		if (filters == null)	{
			result = daoSimple.findAll();
		}else	{
			List<Criterion> criterionList = new ArrayList<Criterion>();
			Iterator entries = filters.entrySet().iterator();
			while (entries.hasNext()) {
				Entry thisEntry = (Entry) entries.next();
				String key = (String) thisEntry.getKey();
				Object value = thisEntry.getValue();
				Criterion criterion = Restrictions.like(key, value + "%");
				criterionList.add(criterion);
			}
			Criterion[] criterions = criterionList.toArray(new Criterion[criterionList.size()]);
			result = daoSimple.findByCriteria(criterions);
		}
		
		return result;
	}

	public void create(String entityName, Object entity) {
		System.out.println("DatastoreServiceImpl.create()...");

		SimpleHibernateDAO daoSimple = (SimpleHibernateDAO) beanFactory.getBean("simpleHibernateDAO");
		daoSimple.setPersistentClass(entityName);

		// persist the entity
		daoSimple.save(entity);
	}

	public void update(String entityName, Object entity) {
		System.out.println("DatastoreServiceImpl.update()...");

		SimpleHibernateDAO daoSimple = (SimpleHibernateDAO) beanFactory.getBean("simpleHibernateDAO");
		daoSimple.setPersistentClass(entityName);

		// persist the entity
		daoSimple.save(entity);
	}

	public void delete(String entityName, Object entity) {
		System.out.println("DatastoreServiceImpl.delete()...");

		SimpleHibernateDAO daoSimple = (SimpleHibernateDAO) beanFactory.getBean("simpleHibernateDAO");
		daoSimple.setPersistentClass(entityName);

		// persist the entity
		daoSimple.delete(entity);
	}
}
